import React, { useMemo } from 'react';

import ReactMarkdown from 'react-markdown';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { vscDarkPlus, oneLight } from 'react-syntax-highlighter/dist/esm/styles/prism';
import rehypeKatex from 'rehype-katex';
import rehypeRaw from 'rehype-raw';
import remarkBreaks from 'remark-breaks';
import remarkGfm from 'remark-gfm';
import remarkMath from 'remark-math';
import 'katex/dist/katex.min.css';

interface MarkdownRendererProps {
	content: string;
	className?: string;
	isDarkMode?: boolean;
	allowHtml?: boolean;
	enableMath?: boolean;
}

/**
 * 增强的Markdown渲染组件
 *
 * 功能：
 * - 支持GitHub风格Markdown (GFM)
 * - 代码语法高亮
 * - 支持数学公式 (可选)
 * - 支持HTML内容渲染 (可选)
 * - 支持亮色/暗色主题切换
 * - 自动将URL转换为链接
 * - 支持表格、任务列表等GFM特性
 *
 * @param content Markdown内容
 * @param className 自定义CSS类名
 * @param isDarkMode 是否使用暗色主题
 * @param allowHtml 是否允许渲染HTML内容
 * @param enableMath 是否启用数学公式支持
 */
const MarkdownRenderer: React.FC<MarkdownRendererProps> = ({
	content,
	className = '',
	isDarkMode = false,
	allowHtml = false,
	enableMath = false
}) => {
	// 根据主题选择代码高亮样式
	const codeStyle = useMemo(() => (isDarkMode ? vscDarkPlus : oneLight), [isDarkMode]);

	// 根据配置选择插件
	const remarkPlugins = useMemo(() => {
		const plugins = [remarkGfm, remarkBreaks];
		if (enableMath) plugins.push(remarkMath);
		return plugins;
	}, [enableMath]);

	// 根据配置选择rehype插件
	const rehypePlugins = useMemo(() => {
		const plugins = [];
		if (allowHtml) plugins.push(rehypeRaw);
		if (enableMath) plugins.push(rehypeKatex);
		return plugins;
	}, [allowHtml, enableMath]);

	// 如果内容为空，返回null
	if (!content) return null;

	return (
		<div className={`markdown-renderer ${isDarkMode ? 'dark-theme' : 'light-theme'} ${className}`}>
			<ReactMarkdown
				remarkPlugins={remarkPlugins}
				rehypePlugins={rehypePlugins}
				components={{
					// 代码块渲染
					code({ node, inline, className, children, ...props }) {
						const match = /language-(\w+)/.exec(className || '');
						return !inline && match ? (
							<SyntaxHighlighter
								style={codeStyle}
								language={match[1]}
								PreTag="div"
								wrapLongLines={true}
								{...props}
							>
								{String(children).replace(/\n$/, '')}
							</SyntaxHighlighter>
						) : (
							<code className={`${className || ''} ${inline ? 'inline-code' : ''}`} {...props}>
								{children}
							</code>
						);
					},
					// 链接渲染
					a({ node, children, href, ...props }) {
						return (
							<a
								href={href}
								target="_blank"
								rel="noopener noreferrer"
								className="markdown-link"
								{...props}
							>
								{children}
							</a>
						);
					},
					// 图片渲染
					img({ node, alt, src, ...props }) {
						return (
							<img src={src} alt={alt || ''} className="markdown-image" loading="lazy" {...props} />
						);
					},
					// 表格渲染
					table({ node, children, ...props }) {
						return (
							<div className="table-container">
								<table className="markdown-table" {...props}>
									{children}
								</table>
							</div>
						);
					}
				}}
			>
				{content}
			</ReactMarkdown>
		</div>
	);
};

// 添加默认样式
const style = document.createElement('style');
style.textContent = `
	.markdown-renderer {
		font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
		line-height: 1.6;
	}

	.markdown-renderer h1,
	.markdown-renderer h2,
	.markdown-renderer h3,
	.markdown-renderer h4,
	.markdown-renderer h5,
	.markdown-renderer h6 {
		margin-top: 1.5em;
		margin-bottom: 0.5em;
		font-weight: 600;
	}

	.markdown-renderer h1 { font-size: 2em; border-bottom: 1px solid #eaecef; padding-bottom: 0.3em; }
	.markdown-renderer h2 { font-size: 1.5em; border-bottom: 1px solid #eaecef; padding-bottom: 0.3em; }
	.markdown-renderer h3 { font-size: 1.25em; }
	.markdown-renderer h4 { font-size: 1em; }

	.markdown-renderer p {
		margin-bottom: 1em;
	}

	.markdown-renderer ul,
	.markdown-renderer ol {
		margin-bottom: 1em;
		padding-left: 2em;
	}

	.markdown-renderer li {
		margin-bottom: 0.5em;
	}

	.markdown-renderer blockquote {
		padding: 0 1em;
		color: #6a737d;
		border-left: 0.25em solid #dfe2e5;
		margin-bottom: 1em;
	}

	.markdown-renderer .inline-code {
		padding: 0.2em 0.4em;
		background-color: rgba(27, 31, 35, 0.05);
		border-radius: 3px;
		font-family: SFMono-Regular, Consolas, Liberation Mono, Menlo, monospace;
		font-size: 85%;
	}

	.markdown-renderer .table-container {
		overflow-x: auto;
		margin-bottom: 1em;
	}

	.markdown-renderer .markdown-table {
		border-collapse: collapse;
		width: 100%;
	}

	.markdown-renderer .markdown-table th,
	.markdown-renderer .markdown-table td {
		padding: 6px 13px;
		border: 1px solid #dfe2e5;
	}

	.markdown-renderer .markdown-table tr {
		background-color: #fff;
		border-top: 1px solid #c6cbd1;
	}

	.markdown-renderer .markdown-table tr:nth-child(2n) {
		background-color: #f6f8fa;
	}

	.markdown-renderer .markdown-image {
		max-width: 100%;
		box-sizing: content-box;
		background-color: #fff;
	}

	.markdown-renderer .markdown-link {
		color: #0366d6;
		text-decoration: none;
	}

	.markdown-renderer .markdown-link:hover {
		text-decoration: underline;
	}

	/* 暗色主题 */
	.markdown-renderer.dark-theme {
		color: #e1e1e1;
	}

	.markdown-renderer.dark-theme h1,
	.markdown-renderer.dark-theme h2 {
		border-bottom-color: #3e4451;
	}

	.markdown-renderer.dark-theme blockquote {
		color: #a0a0a0;
		border-left-color: #4b5364;
	}

	.markdown-renderer.dark-theme .inline-code {
		background-color: rgba(255, 255, 255, 0.1);
	}

	.markdown-renderer.dark-theme .markdown-table th,
	.markdown-renderer.dark-theme .markdown-table td {
		border-color: #3e4451;
	}

	.markdown-renderer.dark-theme .markdown-table tr {
		background-color: transparent;
		border-top-color: #3e4451;
	}

	.markdown-renderer.dark-theme .markdown-table tr:nth-child(2n) {
		background-color: rgba(255, 255, 255, 0.05);
	}

	.markdown-renderer.dark-theme .markdown-link {
		color: #58a6ff;
	}
`;

document.head.appendChild(style);

export default MarkdownRenderer;
